package com.quicks.beauty.server.web;

import com.quicks.beauty.core.dao.WxUserMapper;
import com.quicks.beauty.core.entity.UserOrder;
import com.quicks.beauty.core.entity.WxUser;
import com.quicks.beauty.core.utils.LocalDateTimeUtils;
import com.quicks.beauty.core.vo.UserOrderDetailVO;
import com.quicks.beauty.core.vo.UserOrderVO;
import com.quicks.beauty.server.common.AjaxResult;
import com.quicks.beauty.server.common.RepeatRequest;
import com.quicks.beauty.server.common.StringUtil;
import com.quicks.beauty.server.common.WeiXinUtils;
import com.quicks.beauty.server.service.OrderService;
import com.quicks.beauty.server.service.RedisBillService;
import com.quicks.beauty.server.vos.Front;
import com.quicks.beauty.server.vos.GiftVO;
import com.quicks.beauty.server.vos.InnerTime;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "order")
@Api(tags = "获取用户的订单")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    WeiXinUtils weiXinUtils;
    @Autowired
    WxUserMapper wxUserMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisBillService redisBillService;

    /**
     * 下单
     *
     * @param userId
     * @param productId
     * @param mobile
     * @param username
     * @param num
     * @param kinds
     * @param addressId
     * @param appointTime
     * @return
     */
    @ApiOperation(value = "新增消费兑换订单")
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "form", required = true, dataType = "String"),
            @ApiImplicitParam(name = "productId", value = "商品id", paramType = "form", required = true, dataType = "String"),
            @ApiImplicitParam(name = "mobile", value = "手机号", paramType = "form", required = true, dataType = "String"),
            @ApiImplicitParam(name = "username", value = "用户名", paramType = "form", required = true, dataType = "String"),
            @ApiImplicitParam(name = "num", value = "数量", paramType = "form", required = true, dataType = "String"),
            @ApiImplicitParam(name = "kinds", value = "种类", paramType = "form", required = true, dataType = "String"),
            @ApiImplicitParam(name = "addressId", value = "地址id", paramType = "form", required = true, dataType = "String"),
            @ApiImplicitParam(name = "appointTime", value = "预约时间", paramType = "form", required = true, dataType = "String")
    })
    public AjaxResult comeOrder(@ApiParam String userId, String productId, String mobile, String username, int num, int kinds, String addressId, Long appointTime,Long appointTimeEnd) {
        GiftVO vo = new GiftVO();
        AjaxResult result = new AjaxResult();
        if (kinds == 0) {
            long time = new Date().getTime();
            long before = time + 3600000l;
            if (appointTime < before) {
                result.setSuccess(false);
                result.setMsg("预约时间不符合");
                return result;
            }
            boolean endpoint = LocalDateTimeUtils.getEndpoint(appointTime);
            if (!endpoint) {
                result.setSuccess(false);
                result.setMsg("预约时间不符合");
                return result;
            }
        }
        vo.setUserId(userId).setProductId(productId)
                .setMobile(mobile).setUsername(username)
                .setNum(num).setKinds(kinds).setAddressId(addressId)
                .setAppointTime(appointTime).setAppointTimeEnd(appointTimeEnd);
        int i = 0;
        try {
            i = orderService.addUserOrder(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (i > 0) {
            result.setSuccess(true);
            result.setData(i);
        } else {
            result.setSuccess(false);
            result.setMsg("下单失败");
        }
        return result;
    }


    @ApiOperation(value = "add订单-(也称作:我的礼品列表)")
    @RequestMapping(value = "addOrder", method = RequestMethod.POST)
    public AjaxResult genOrder(@ModelAttribute GiftVO giftVO){
        AjaxResult result = new AjaxResult();
        int kinds = giftVO.getKinds();
        long appointTime = giftVO.getAppointTime();
/*        if (kinds == 0) {
            long time = new Date().getTime();
            long before = time + 3600000l;
            if (appointTime < before) {
                result.setMsg("预约时间不符合");
                result.setSuccess(false);
                return result;
            }
            boolean endpoint = LocalDateTimeUtils.getEndpoint(appointTime);
            if (!endpoint) {
                result.setMsg("预约时间不符合");
                result.setSuccess(false);
                return result;
            }
        }*/

        // addOrderTwo

        int i = 0;
        try {
            i = orderService.addOrderTwo(giftVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (i > 0) {
           String orderId =  orderService.getOrderId(giftVO.getUserId());
            if(Integer.parseInt(giftVO.getTradeType())==0){

                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("needWXPay", false);
                hashMap.put("orderId", orderId);
                hashMap.put("orderMoney", 0);
                result.setData(hashMap);
            }else{
                WxUser wxUser = wxUserMapper.selectByPrimaryKey(giftVO.getUserId());
                UserOrder uo =  orderService.getOrderDetail(giftVO.getUserId());
                String xmlRequest = weiXinUtils.generateXmlRequest(uo.getId(), wxUser.getOpenId(), uo.getMoney(), uo.getOrderCodes(), String.format("商品支付,订单编号：%s", uo.getOrderCodes()));
                RepeatRequest results = weiXinUtils.preparePayToGenerateXMLResponse(xmlRequest);
                results.setOrderid(uo.getId());
                stringRedisTemplate.opsForValue().set(orderId+"&"+giftVO.getUserId(),orderId,30, TimeUnit.MINUTES);

                Map<String, Object> map = StringUtil.entityToMap(results);
                map.put("needWXPay", true);
                map.put("orderMoney", uo.getMoney());
                //redisBillService.pushExpireOrder(giftVO.getUserId(), uo.getId());
                result.setData(map);
            }
            result.setSuccess(true);


        } else {
            result.setSuccess(false);
            result.setMsg("下单失败");
        }
        return result;
    }


    /**
     * 我的礼品列表
     *
     * @param pageNum
     * @param pageSize
     * @param userId
     * @return
     */
    @ApiOperation(value = "我的订单列表-(也称作:我的礼品列表)")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID，", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页面，", paramType = "query", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "数量，", paramType = "query", required = true, dataType = "Integer")
    })
    public AjaxResult listOrders(@RequestParam("pageNum") Integer pageNum,
                                 @RequestParam("pageSize") Integer pageSize,
                                 @RequestParam("userId") String userId) {
        pageSize = pageSize == null ? super.pageSize : pageSize;
        AjaxResult result = new AjaxResult();
        pageNum = pageNum == null ? super.pageNum : pageNum;
        try {
            List<UserOrderVO> pager = orderService.getProductPager(userId, pageNum, pageSize);
            result.setSuccess(true);
            result.setData(pager);
            result.setMsg("ok");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("数据异常");
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 获取当前礼品详情
     *
     * @param orderId
     * @return
     */
    @ApiOperation(value = "当前订单详情--(也称作:当前礼品详情)")
    @RequestMapping(value = "item", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID，", paramType = "query", required = true, dataType = "Integer")
    })
    public AjaxResult getOrderById(@RequestParam("orderId") String orderId) {
        AjaxResult result = new AjaxResult();
        try {
            UserOrderDetailVO vo = orderService.getUserOrderDetailVO(orderId);
            result.setSuccess(true);
            result.setData(vo);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("数据异常");
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping(value = "/times")
    @ResponseBody
    public AjaxResult f2() {
        AjaxResult result = new AjaxResult();
        LocalDateTime now = LocalDateTime.now();
        long l = now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("MM月dd日 (EE)", Locale.CHINA);
        DateTimeFormatter nowPattern = DateTimeFormatter.ofPattern("MM月dd日 ",Locale.CHINA);

        LocalDateTime night = now.withHour(9).withMinute(0).withSecond(0).withNano(0);
        ArrayList<Front> s = new ArrayList<>();
        for (int j = 1; j < 8; j++) {
            Front s0 = new Front();
            ArrayList<InnerTime> s0t = new ArrayList<>();
            if(j==1){
                String days = night.format(nowPattern);
                s0.setDays(days+"(今天)");
            } else {
                String days = night.format(ofPattern);
                String old = days.replace("星期", "周");
                s0.setDays(old);
            }
            for (int i = 1; i < 7; i++) {
                int h0 = night.getHour();
                int h1 = night.plusHours(2).getHour();

                long h0s = night.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                long h1s = night.plusHours(2).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

//                boolean a = (h0s>l && h1s<l);
                boolean b = h1s >l+3600000l;
                if( b){
                    InnerTime time = new InnerTime(h0 + ":00" + "--" + h1 + ":00", h0s + "--" + h1s);
                    s0t.add(time);
                } else {
                    InnerTime time = new InnerTime(h0 + ":00" + "--" + h1 + ":00", h0s + "--" + h1s,false);
                    s0t.add(time);
                }
                night = night.plusHours(2);
            }
            s0.setTime(s0t);
            s.add(s0);
            night = night.plusDays(1).withHour(9).withMinute(0).withSecond(0).withNano(0);
        }
        result.setSuccess(true);
        result.setData(s);
        return result;
    }
    @RequestMapping(value = "cancelOrder")
    public AjaxResult cancelOrder(String orderId,String userId){
        AjaxResult result = new AjaxResult();
        try{
            orderService.expirePoints(userId,orderId);
            result.setSuccess(true);
            result.setMsg("ok");
        }catch(Exception e ){
            result.setSuccess(false);
            result.setMsg("no");
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping(value = "toPay")
    public AjaxResult toPay(String orderId,String userId){
        AjaxResult result = new AjaxResult();
        WxUser wxUser = wxUserMapper.selectByPrimaryKey(userId);
        UserOrder uo = orderService.getOrderById(orderId);
        String xmlRequest = weiXinUtils.generateXmlRequest(orderId, wxUser.getOpenId(), uo.getMoney(), uo.getOrderCodes(), String.format("商品支付,订单编号：%s", uo.getOrderCodes()));
        RepeatRequest results = weiXinUtils.preparePayToGenerateXMLResponse(xmlRequest);
        results.setOrderid(orderId);
        stringRedisTemplate.opsForValue().set(orderId+"&"+userId,orderId,30, TimeUnit.MINUTES);

        Map<String, Object> map = StringUtil.entityToMap(results);
        map.put("needWXPay", true);
        map.put("orderMoney", uo.getMoney());
       // redisBillService.pushExpireOrder(userId, orderId);
        result.setData(map);
        result.setMsg("ok");
        result.setSuccess(true);
        return result;
    }
}
